//
//  FeedParser.m
//  DemoRSSReader
//
//  Created by Bruce McMoran on 7/16/11.
//  Copyright 2011 myself. All rights reserved.
//

#import "FeedParser.h"
#import "GTMDefines.h"
#import "GTMNSString+HTML.h"

@implementation FeedParser
@synthesize feedURL, feedConnection, parser, delegate;
@synthesize currentElement, feedItem, feedItemsArray;


-(id) initWithFeedURL:(NSURL *)feed 
{
    if ((self = [self init])) 
    {
        feedURL = feed;
        
        feedItemsArray = [[NSMutableArray alloc] init];
    }
    
    return self;
}

-(BOOL) parse
{
    BOOL success;
    NSURLResponse* response;
    NSError* error = nil;
    NSData* feedData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:feedURL] returningResponse:&response error:&error];
    if(feedData && !error)
    {
        NSXMLParser* p = [[NSXMLParser alloc] initWithData:feedData];
        self.parser = p;
        [p release];
        [parser setShouldProcessNamespaces:YES];
        if(parser) {
            parser.delegate = self;
            [parser parse];
        }
        success = YES;
    }
    return success;
    
}

-(void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"Started parsing");
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"Finished parsing. Found %d items", [feedItemsArray count]);
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"item"]) {
        feedItem = [[[NSMutableDictionary alloc] init ] autorelease];
    }
    currentElement = [NSMutableString stringWithString:elementName];
    return;
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"item"]) {
        NSLog(@"Created item with %d elements", [feedItem count]);
        [feedItemsArray addObject:feedItem];
        feedItem = nil;
    }
    currentElement = nil;
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (currentElement) {
        // Parse out html entities with http://www.columbia.edu/kermit/utf8-t1.html
        
        [feedItem setValue:[string gtm_stringByUnescapingFromHTML] forKey:currentElement];
    }
}

-(void)dealloc
{
    /*
     @synthesize feedURL, feedConnection, parser, delegate;
     @synthesize currentElement, feedItem, feedItemsArray;
    */
    [super dealloc];
    parser = nil;
    feedItem = nil;
    feedURL = nil;
    feedConnection = nil;
    feedItemsArray = nil;
    currentElement = nil;
    delegate = nil;
}

@end

